<template>
  <div class="login-container">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label>用户名</label>
        <input v-model="form.username" type="text" required />
      </div>
      <div class="form-group">
        <label>密码</label>
        <input v-model="form.password" type="password" required />
      </div>
      <button type="submit" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { loginAPI } from '@/api/auth';
import { useAuthStore } from '@/stores/auth';

const router = useRouter();
const authStore = useAuthStore();
const form = reactive({
  username: '',
  password: ''
});

const loading = ref(false);

const handleLogin = async () => {
  loading.value = true;
  try {
    const response = await loginAPI(form);
    // 确保response包含token字段
    if (response && response.token) {
      authStore.setAuth(response)
      // localStorage.setItem('token', data.token);
      
      // 重定向到原始路径或首页
      const redirect = router.currentRoute.value.query.redirect || '/home';
      router.push(redirect);
    } else {
      throw new Error('登录响应中缺少token字段');
    }
  } catch (error) {
    alert('登录失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
.form-group {
  margin-bottom: 15px;
}
</style>